//
//  UIView+HDActionShare.m
//  SYActionSheetView
//
//  Created by D on 15/4/27.
//  Copyright (c) 2015年 SY. All rights reserved.
//

#import "HDActionShare.h"
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "sdkCall.h"
#import "WXApi.h"
#import "HDUserInforHttpRequestManger.h"
#import "HDAppDelegate.h"


@interface HDActionShare ()

@property (nonatomic, strong) NSMutableArray *btnArray;

@property (nonatomic, assign) BOOL isShow;

@property (nonatomic, copy) NSString *aTitle;
@property (nonatomic, copy) NSString *aCancleTitle;

@end


@implementation HDActionShare
@synthesize discuz_id = _discuz_id;
@synthesize topic_id = _topic_id;
@synthesize title = _title;
@synthesize result_share = _result_share;
@synthesize pic = _pic;
@synthesize url = _url;
@synthesize content = _content;
-(id)initWithDiscuzId:(NSString*)discuz_id TopicId:(NSString*)topic_id
{
    self = [super init];
    _btnArray = [NSMutableArray array];
    if (self) {
         HDAppDelegate *appDelegate = (HDAppDelegate *)[UIApplication sharedApplication].delegate;
        
        icons = @[@"wx_light.png",@"pyq_light.png",@"qq_light.png",@"qzone_light.png"];
        iconNames = @[@"微信",@"朋友圈",@"QQ",@"QZone"];
        _topic_id = topic_id;
        _discuz_id = discuz_id;
        _title = [NSString string];
        _pic = [NSString string];
        _url = [NSString string];
        _content = [NSString string];
        self.frame = appDelegate.window.screen.bounds;
        [self initUI];
 
        _result_share = [JKRemoteResult target:self action:@selector(shareMsg:)];
        [self getShareMessage];
        
    }
    return self;
    
}

-(void)getShareMessage
{
    HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
    
    [httpManager getShareMessageWithParams:_discuz_id topic_id:_topic_id result:_result_share];
}
-(void)shareMsg:(JKRemoteResult*)rt
{
    if (rt.failure) {
        
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"分享失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [av show];
        [self removeFromSuperview];
        return;
    }
    if (rt.response.status == 0) {
        _content = [rt.info objectForKey:@"content"];
        _title = [rt.info objectForKey:@"title"];
        _pic = [rt.info objectForKey:@"face"];
        _url = [rt.info objectForKey:@"url"];
        
        UIImageView * shareImage = [[UIImageView alloc]init];
        [shareImage sd_setImageWithURL:[NSURL URLWithString:_pic] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            NSData * data = UIImageJPEGRepresentation(image,1.0);
            [[SDImageCache sharedImageCache] storeImage:image recalculateFromImage:YES imageData:data forKey:@"shareImage" toDisk:YES];
        }];
        
    }else
    {
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"分享失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [av show];
        [self removeFromSuperview];
    }
    
    
}

-(void)initUI
{
//    CGFloat Hight = self.frame.size.height;
//    CGFloat v1H = Hight/4;
//    CGFloat v2H = v1H/3*2;
//    CGFloat W = self.frame.size.width;
    CGFloat widthEachFour = [self.ubo fw:0.25];
    self.userInteractionEnabled = YES;
    
    transparentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds))];
    transparentView.backgroundColor = [UIColor blackColor];
    transparentView.alpha = 0.0f;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSYActionShare)];
    tap.numberOfTapsRequired = 1;
    [transparentView addGestureRecognizer:tap];
    
    CGFloat btnWidth = CGRectGetWidth(transparentView.frame) - UF(24),btnHeight = 45;
//    btnSpace = 10,normalSpace = 30;
    
    actionSheetHeight = btnHeight * _btnArray.count + 164;
//    btnSpace * (_btnArray.count - 2) + normalSpace * 3;
    
    actionSheetView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, actionSheetHeight)];
    actionSheetView.backgroundColor = [UIColor whiteColor];
    actionSheetView.layer.borderWidth = 1.0;
    actionSheetView.layer.borderColor = kRGBRef(87.0, 87.0, 87.0, 1.0);
    actionSheetView.alpha = 0.95;
    [self addSubview:actionSheetView];
    
    __block CGRect frame = CGRectZero;
//     actionSheetHeight = btnHeight * _btnArray.count + 96;
//    actionSheetHeight = btnHeight * 2 + btnSpace * (2 - 2) + normalSpace * 2;
//    normalSpace =  10;
//    actionSheetHeight += normalSpace;
    
    frame = actionSheetView.frame;
    frame.size.height = actionSheetHeight;
    actionSheetView.frame = frame;

    for (int i = 0;  i < 4; i++) {
        
        UIButton * icon = [[UIButton alloc]initWithFrame:CGRectMake((i+1)*widthEachFour - (widthEachFour+54)/2, UF(32), 54, 54)];
        icon.tag = i;
        
        [icon setBackgroundImage:[UIImage imageNamed:[icons objectAtIndex:i]] forState:UIControlStateNormal];
        icon.tintColor = [UIColor blackColor];
        //        icon.backgroundColor = [UIColor grayColor];
        [icon addTarget:self action:@selector(Third:) forControlEvents:UIControlEventTouchUpInside];
        [actionSheetView addSubview:icon];
        
        UILabel * iconLab = [[UILabel alloc]initWithFrame:CGRectMake(i*widthEachFour, 54+UF(44), widthEachFour, UF(10*2))];
        iconLab.text = [iconNames objectAtIndex:i];
        UIFont * font = [UIFont systemFontOfSize:13];
        [iconLab setFont:font];
        [iconLab setTextAlignment:NSTextAlignmentCenter];
        [actionSheetView addSubview:iconLab];
        
    }
    UIButton * canle = [[UIButton alloc]initWithFrame:CGRectMake(UF(24),54+UF(86) , self.ubo.width-2*UF(24), 45)];
    canle.backgroundColor = [UIColor whiteColor];
    [canle setTitle:@"取消" forState:UIControlStateNormal];
    [canle setBackgroundImage:[[UIImage imageNamed:@"actionsheet"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)] forState:UIControlStateNormal];
    [canle setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [canle addTarget:self action:@selector(cancleEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    [actionSheetView addSubview:canle];

    
    
}

-(void)Third:(UIButton*)sender
{
    switch (sender.tag) {
        case 0:
        {
            //            [self sendLinkContent:0];
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = _title;
            message.description = _content;
            
            [message setThumbImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:@"shareImage"]];
            
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = _url;
            
            message.mediaObject = ext;
            message.mediaTagName = @"";
            
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            req.scene = WXSceneSession;
            [WXApi sendReq:req];
            
            
            
        }
            break;
        case 1:
        {
            WXMediaMessage *message = [WXMediaMessage message];
            message.title =_title;
            message.description = _content;
            [message setThumbImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:@"shareImage"]];
            
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = _url;
            
            message.mediaObject = ext;
            message.mediaTagName = @"";
            
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            req.scene = WXSceneTimeline;
            [WXApi sendReq:req];
            
            
            
        }
            break;
        case 2:
        {
            
            [sdkCall getinstance];
            NSURL *previewURL = [NSURL URLWithString:_pic];
            NSURL* url = [NSURL URLWithString:_url];
            
            QQApiNewsObject* img = [QQApiNewsObject objectWithURL:url title:_title description:_content previewImageURL:previewURL];
            SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
            [self handleSendResult:sent];
            
        }
            break;
        case 3:
        {
            [sdkCall getinstance];
            
            NSURL *previewURL = [NSURL URLWithString:_pic];
            NSURL* url = [NSURL URLWithString:_url];
            
            QQApiNewsObject* img = [QQApiNewsObject objectWithURL:url title:_title description:_content previewImageURL:previewURL];
            SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
            QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
            [self handleSendResult:sent];
        }
            break;
            
        default:
            break;
    }
    [self hideSYActionShare];
    [self removeFromSuperview];
}


- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        default:
        {
            break;
        }
    }
}


- (void)cancleEvent:(id)sender
{
    SYLog(@"cancleEvent");
    
    [self hideSYActionShare];
}


#pragma mark -
#pragma mark PickerView show/hide

- (void)hideSYActionShare
{
    [UIView animateWithDuration:0.2
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^() {
                         transparentView.alpha = 0.0;
                         
                         self.center = CGPointMake(CGRectGetWidth(self.frame) / 2.0, CGRectGetHeight([UIScreen mainScreen].bounds) + CGRectGetHeight(self.frame) / 2.0);
                         
                         //self.frame = CGRectMake(0, KDeviceHeight, kDeviceWidth, KDeviceHeight - 64);
                     } completion:^(BOOL finished) {
                         [transparentView removeFromSuperview];
                         [self removeSelf];
                     }];
}

- (void)removeSelf
{
    [self removeFromSuperview];

    self.isShow = NO;
    
   }

- (void)showSYActionSheet
{
    [self showSYActionSheetInView:kWindow];
}

- (void)showSYActionSheetInView:(UIView *)view
{
    CGFloat vH = CGRectGetHeight(view.frame);
    
    self.frame = CGRectMake(0, KDeviceHeight, kDeviceWidth, actionSheetHeight);
    actionSheetY = vH - actionSheetHeight;
    
    [view addSubview:self];
    [view insertSubview:transparentView belowSubview:self];
    
    self.isShow = YES;
    
    [UIView animateWithDuration:0.2
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^() {
                         transparentView.alpha = 0.4;
                         self.frame = CGRectMake(0, actionSheetY, kDeviceWidth, actionSheetHeight);
                     }
                     completion:^(BOOL finished) {}];
}
@end







